<?php

namespace app\api\controller;


use app\admin\model\config\Basics;
use app\admin\model\goods\Goods;
use app\admin\model\goods\ShopGoodsSpecs;
use app\admin\model\shop\Shop;
use app\admin\model\user\Address;
use app\common\controller\Api;
use app\common\helpers\ImageUtil;
use app\common\helpers\MapUtil;
use app\common\keloop\Delivery;
use app\common\keloop\KeloopSdk;
use think\Db;
use think\Log;
use think\Model;
use function fast\e;
use think\exception\PDOException;
use think\exception\ValidateException;
/**
 * 订单接口
 */
class Order extends Api
{
    protected $noNeedLogin = ['relateStore','getStores','getOrderNum'];
    protected $noNeedRight = ['*'];


    /**
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * 计算价格
     */
    public function calculation()
    {
        $goods_id= $this->request->param('goods_id');
        $shop_id= $this->request->param('shop_id');
        $num= $this->request->param('num');
        $child= $this->request->param('child');
        $address_id= $this->request->param('address_id');
        $Shop = Shop::get(['id'=>$shop_id]);
        if(!$Shop || ($Shop['status'] == '2' || $Shop['is_del'] == '1')){
            $this->error("商铺已下架");
        };
        $goods = Goods::field('id,name,price,content,imgs')->where(['id'=>$goods_id])->find();
        if(!$goods || !$Shop){
            $this->error("参数错误");
        }

        $Basics =  Basics::get(1);
        $goods_price = $goods['price'] * $num;
        $packing_price = $Basics['packing_fee'] * $num;
        $minitype = [];
        if($child){
            $childArr =  explode(',',$child);
            $SpecsList = ShopGoodsSpecs::where('id','in',$childArr)->select();
            if($SpecsList){
                foreach ($SpecsList as $v){
                    $minitype[]=$v['name'];
                    if($v['price'] > 0){
                        $goods_price += $v['price'] * $num;
                    }
                }
            }
        }
        $distribution_price = 0;
        if($address_id){
            $Address =  Address::get(['id'=>$address_id]);
            if(!$Address){
                $this->error("地址错误");
            }
            $distance = MapUtil::distance($Shop['lat'],$Shop['lng'],$Address['lat'],$Address['lng']) ;
            $distribution_price = $distance <= 1 ?  $Basics['distribution_fee'] : round(round($distance,0) * $Basics['distribution_fee'],2);

        }
        $data=[
            'goods_price'=>$goods_price, //商品费用
            'packing_price'=>$packing_price, //打包费
            'distribution_price'=>$distribution_price, //配送费
            'actual_price'=>$goods_price + $packing_price + $distribution_price,
            'minitype'=>$minitype,
            'shop_id'=>$shop_id,
            'goods_id'=>$goods_id,
            'num'=>$num,
        ];
        $this->success('successful', $data);

    }

    /**
     *
     * 确认订单
     */
    public function orderConfirm()
    {
        $user = $this->auth->getUser();
        $returnurl = $this->request->param('returnurl', '');
        $goods_id= $this->request->param('goods_id');
        $shop_id= $this->request->param('shop_id');
        $num= $this->request->param('num');
        $child= $this->request->param('child');
        $address_id= $this->request->param('address_id');
        $Shop = Shop::get(['id'=>$shop_id]);
        if(!$Shop || ($Shop['status'] == '2' || $Shop['is_del'] == '1')){
            $this->error("商铺已下架");
        };
        $goods = Goods::field('id,name,price,content,imgs')->where(['id'=>$goods_id])->find();
        if(!$goods || !$Shop){
            $this->error("参数错误");
        }
        if($num <= 0){
            $this->error("请选择数量");
        }
        $Basics =  Basics::get(1);
        $goods_price = $goods['price'] * $num;
        $packing_price = $Basics['packing_fee'] * $num;
        $minitype = [];
        if($child){
            $childArr =  explode(',',$child);
            $SpecsList = ShopGoodsSpecs::where('id','in',$childArr)->select();
            if($SpecsList){
                foreach ($SpecsList as $v){
                    $minitype[]=$v['name'];
                    if($v['price'] > 0){
                        $goods_price += $v['price'] * $num;
                    }
                }
            }
        }
        $address =  Address::get(['id'=>$address_id]);
        if(!$address){
            $this->error("请选择收货地址");
        }
        $distance = MapUtil::distance($Shop['lat'],$Shop['lng'],$address['lat'],$address['lng']) ;
        $distribution_price = $distance <= 1 ?  $Basics['distribution_fee'] : round(round($distance,0) * $Basics['distribution_fee'],2);
        $orderid = "wx".time().rand(100000,999999);
        $lngLat = (new MapUtil)->bdGcj($address['lng'],$address['lat']);
        $actual_price = $goods_price + $packing_price + $distribution_price;
        $data=[
            'order_number'=>$orderid,
            'goods_name'=>$goods['name'],
            'goods_img'=>$goods['imgs'],
            'status'=>0,
            'uid' => $user['id'],
            'shop_id'=>$shop_id,
            'goods_id'=>$goods_id,
            'guige'=>implode(',',$minitype),
            'price'=>$goods_price,//商品金额
            'pack_price'=>$packing_price,//打包费
            'distribution_price'=>$distribution_price,//配送费
            'num'=>$num,
            'actual_price'=>$actual_price,//实际支付金额
            'order_time'=>date('Y-m-d H:i:s'),
            'is_hy_order'=>($user['member_expire_time'] && strtotime($user['member_expire_time']) >= time()) ? 1 : 0,
            'is_tk'=>$user['is_tk'],
            'harvest_address'=>$address['receipt_address'].$address['address'],//收货地址收
            'harvest_user'=>$address['name'],//收货人
            'harvest_phone'=>$address['mobile'],//收货人电话
            'harvest_lng'=>$lngLat[0],
            'harvest_lat'=>$lngLat[1],
        ];
        $result = \app\admin\model\shop\Order::create($data);
        if(!$result)   $this->error('生成订单失败');
        $this->success('successful', ['order_number'=>$orderid,'actual_price'=>$data['actual_price']]);
    }

    /**
     * 订单列表
     */
    public function orderList(){

        Task::unpaidOrder();
        $page = $this->request->param('page',1);//页码
        $pageSize = $this->request->param('pageSize',5);//每页展示数量
        $status = $this->request->param('status');//状态 1 待付款 2处理中 3已结束
        $user = $this->auth->getUser();
        $where['uid'] = $user['id'];
        if($status){
            switch ($status){
                case '1':
                    $where['status'] = 0;
                    break;
                case '2':
                    $where['status'] = ['in',[2,3,4,5,6]];
                    break;
                case '3':
                    $where['status'] = ['in',[7,8,9,10,11,12,13]];
                    break;
                default:
                    break;
            }
        }
        $model = (new \app\admin\model\shop\Order())
            ->field('order_number,goods_name,goods_img,num,guige,actual_price,status,order_time,is_hy_order')
            ->where($where)
            ->order('order_time desc')
            ->paginate($pageSize, '', ['page' => $page, 'list_rows' => $pageSize]);
        $total= $model->total();
        $list =  $model->items();
        if($list){
            foreach ($list as &$v){
                $v['goods_img'] = ImageUtil::handle($v['goods_img']);
                $v['is_huigou'] = ($v['status'] == 1 && $v['is_hy_order'] == 1) ? 1 : 0;
            }
        }
        $this->success('successful', array("total" =>$total , "list" => $list));
    }

    /**
     * 订单详情
     */
    public function orderDetials(){
        Task::unpaidOrder();
        $order_number = $this->request->param('order_number');
        $info = \app\admin\model\shop\Order::get(['order_number'=>$order_number]);
        $data=[
            'order_number'=>$info['order_number'],
            'status'=>$info['status'],
            'goods_price'=>$info['price'], //商品费用
            'packing_price'=>$info['pack_price'], //打包费
            'distribution_price'=>$info['distribution_price'], //配送费
            'actual_price'=>$info['actual_price'],
            'minitype'=>explode(',',$info['guige']),
            'num'=>$info['num'],
            'order_time'=>$info['order_time'],
            'payment_time'=>$info['payment_time'],//支付时间
            'end_time'=>$info['end_time'], //结束时间
            'harvest_address'=>$info['harvest_address'], //收货地址收
            'harvest_user'=>$info['harvest_user'], //收货人
            'harvest_phone'=>$info['harvest_phone'], //收货人电话
            'overdue_time'=>strtotime($info['order_time'])+1800,
            'is_huigou' => ($info['status'] == 1 && $info['is_hy_order'] == 1) ? 1 : 0
        ];
        $this->success('successful', $data);
    }

    /**
     * 取消订单
     */
    public function cancelOrder(){
        $user = $this->auth->getUser();
        $order_number = $this->request->param('order_number');
        $row=(new \app\admin\model\shop\Order())->get(['order_number'=>$order_number,'uid'=>$user['id']]);
        if($row['refund_status'] == '1'){
            $this->error('退款中');
        }
        if($row['refund_status'] == '2'){
            $this->error('已退款,注意查收');
        }
        $refund_number = \app\common\controller\Common::orderRefundNumber();

        $row->before_refund_status= $row->status;
        $row->end_time =date('Y-m-d H:i:s');
        if(in_array($row['status'],['1','2'])){ //目前只有2和3的状态才走微信退款
            $row->refund_number=$refund_number;
            $row->apply_time=date('Y-m-d H:i:s');
            $row->refund_time = date('Y-m-d H:i:s');
            $row->refund_status =2;
            $res =  \app\common\controller\Common::orderRefund($row,$refund_number);
            if($res['result_code'] != 'SUCCESS'){
                Db::rollback();
                $this->error('取消失败',['msg'=>$res['return_msg']]);
            }
        }
        $row->status=8; //用户取消
        $result = $row->allowField(true)->save();
        if (false === $result) {
            $this->error('取消失败');
        }
        $this->success('取消成功');
    }

    /**
     * 确认回购
     */
    public function orderHg(){
        $user = $this->auth->getUser();
        $order_number = $this->request->param('order_number');
        $info = \app\admin\model\shop\Order::get(['order_number'=>$order_number,'uid'=>$user['id']]);
        if($info['is_hy_order'] == 1 && $info['status'] == 1){ //判断是否支付和会员下单
            $result = false;
            Db::startTrans();
            try {
                $Basics = Basics::get(1);
                if($Basics['distribution_lvl'] != '1'){
                    Common::distribution($info); //分销
                }
                if($Basics['member_buyback'] > 0){ //订单回购
                    \app\common\model\User::money($info['actual_price'] * $Basics['member_buyback'],$user['id'],'订单收益',1,$info['id']);
                }
                $result = (new \app\admin\model\shop\Order())->where(['order_number'=>$order_number,'uid'=>$user['id']])->update(['status'=>12,'end_time'=>date('Y-m-d H:i:s')]);
                Db::commit();
            } catch (ValidateException|PDOException|Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if($result){
                $this->success('操作成功');
            }else{
                $this->error('重复操作');
            }
        }else{
            $this->error('操作失败');
        }
    }

    /**
     * 提货
     */
    public function orderTh(){
        $user = $this->auth->getUser();
        $order_number = $this->request->param('order_number');
        $info = \app\admin\model\shop\Order::get(['order_number'=>$order_number,'uid'=>$user['id'],'is_hy_order'=>1]);
        if($info['status'] == 1){ //判断是否支付订单
            $Order =  (new \app\admin\model\shop\Order());
            $result = $Order->where(['order_number'=>$order_number,'uid'=>$user['id']])->update(['status'=>2]);
            if($result){
                $this->success('操作成功');
            }else{
                $this->error('重复操作');
            }
        }else{
            $this->error('操作失败');
        }
    }

    /**
     *  获取快跑者配送订单的配送员的最新坐标
     */
    public function getCourierTag(){
        $order_number = $this->request->param('order_number');
        try {
            // 封装参数
            $para = [
                'trade_no' => $order_number
            ];
            // 创建 SDK 实例
            $sdk = new KeloopSdk();
            // 调用 getCourierTag 方法
            $result = $sdk->getCourierTag($para);
            // 业务逻辑处理
            if (is_null($result)) {
                exit('获取订单配送员坐标失败');
            } else if (is_array($result)) {
                if ($result['code'] == 200) {
                    exit('success');
                } else {
                    exit('错误信息：' . $result['message']);
                }
            } else {
                exit('接口调用异常');
            }
        } catch (Exception $e) {
            exit('接口调用异常：' . $e->getMessage());
        }
    }


    /**
     * 确认收货
     */
    public function confirmReceipt(){
        $user = $this->auth->getUser();
        $order_number = $this->request->param('order_number');
        $model = new \app\admin\model\shop\Order();
        $info = $model->where('order_number',$order_number)
            ->where('uid',$user['id'])->find();
        if($info){
            if($info['status'] == '6'){
                $Basics = Basics::get(1);
                Db::startTrans();
                $data =[
                    'harvest_time'=>$info['service_time'],
                    'end_time'=>date('Y-m-d H:i:s'),
                    'status'=>'7'
                ];
                $result = \app\admin\model\shop\Order::update($data,['order_number'=>$order_number]);
                if(!$result) {
                    Db::rollback();
                    return false;
                }
                if($info['is_hy_order'] == 1 && $Basics['distribution_lvl'] != '1'){
                   $fx = Common::distribution($info); //分销
                    if(!$fx) {
                        Db::rollback();
                        return false;
                    }
                }
                Db::commit();
                $this->success('已收货');
            }else{
                $this->error('该订单还没有送达');
            }
        }else{
            $this->error('没找到该订单');
        }
    }

    public function getOrderNum()
    {
        $num = \app\admin\model\shop\Order::where('status','2')->count();
        return $this->success('获取成功',$num);
    }


    public function getStores(){
        // 创建 SDK 实例
        $sdk = new KeloopSdk();
        // 调用 createOrder 方法
        $result = $sdk->getStores(['shop_id'=>'4']);
        var_dump($result);exit;
    }

    public function feiyong(){
        $order = \app\admin\model\shop\Order::get(['order_number'=>'wx1678070494106399']);
        $res = Delivery::queryDadaFeeOrder($order);
        var_dump($res);exit;
    }

    public function getOrderTrack(){
        $order_number = $this->request->param('order_number');
        $res = Delivery::getOrderTrack($order_number);
        var_dump($res);exit;
    }


    public function getOrderTransporterPosition(){
        $order_number = $this->request->param('order_number');
        $res = Delivery::getOrderTransporterPosition([$order_number]);
        var_dump($res);exit;
    }

}
